<template>
	<div class="home-container layout-pd">
		<el-row :gutter="15" class="home-card-one mb15">
			<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-for="(v, k) in state.homeOne" :key="k" v-loading="state.loading"
				:class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }">
				<div class="home-card-item flex" v-if="v">
					<div class="flex-margin flex w100" :class="` home-one-animation${k}`">
						<div class="flex-auto">
							<span class="font30">{{ v.count }}</span>
							<span class="ml5 font16"
								:style="{ color: v.scale > 0 ? '#6690F9' : v.scale < 0 ? '#FF6462' : '' }"
								v-if="v.scale != null">{{ v.scale }}%</span>
							<div class="mt10">{{ v.title }}</div>
						</div>
						<div class="home-card-item-icon flex" :style="{ background: `var(${v.iconBackcolor})` }">
							<SvgIcon :size="30" :name="v.icon" class="flex-margin" :color="`var(${v.iconColor})`" />
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-two mb15">
			<el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16" v-loading="state.loading1">
				<div class="home-card-item">
					<div style="height: 100%" ref="homeLineRef"></div>
				</div>
			</el-col>
			<el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media" v-loading="state.loading2">
				<div class="home-card-item">
					<div>
						<h4 style="font-size: 15px;margin-bottom: 5px;">平台做题数量统计</h4>
						<div style="display: flex;align-items: center;">
							<el-date-picker v-model="state.timeInterval" type="daterange" range-separator="-"
								start-placeholder="开始时间" end-placeholder="结束时间"
								:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X'
								:shortcuts="shortcuts" size="small" />
							<el-select v-model="state.company_id" filterable placeholder="请选择所属公司" autocomplete="off" size="small" style="margin-left: 10px;" clearable>
								<el-option v-for="(item, index) in state.companys" :key="item.id" :label="item.title"
									:value="item.id"></el-option>
							</el-select>
							<el-button type="primary" @click="getShujuRound(state.timeInterval,state.company_id)" size="small"
								style="margin-left: 10px;">筛选</el-button>
						</div>
					</div>
					<div style="height: calc(100% - 44px)" ref="homePieRef"></div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-three mb15">
			<el-col :xs="24" class="home-media" v-loading="state.loading3">
				<div class="home-card-item">
					<div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
						<h4 style="font-size: 15px;margin-bottom: 5px;">公司积分统计图</h4>
						<div style="display: flex;align-items: center;">
							<el-select v-model="state.platform_id" filterable placeholder="请选择所属渠道" autocomplete="off" size="small" style="margin-right: 10px;" clearable>
								<el-option v-for="(item, index) in state.paltform" :key="item.id" :label="item.cname"
									:value="item.id"></el-option>
							</el-select>
							<el-date-picker v-model="state.timeIntervalCompany" type="daterange" range-separator="-"
								start-placeholder="开始时间" end-placeholder="结束时间"
								:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X'
								:shortcuts="shortcuts" size="small" />
							<el-button type="primary" @click="getShujuPlatform(state.timeIntervalCompany,state.platform_id)" size="small"
								style="margin-left: 10px;">筛选</el-button>
						</div>
					</div>
					<div style="height: calc(100% - 54px)" ref="homeBarRef"></div>
					<!-- <div style="height: 100%" ref="homeBarRef"></div> -->
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-three mb15">
			<el-col :xs="24" class="home-media" v-loading="state.loading4">
				<div class="home-card-item">
					<div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
						<h4 style="font-size: 15px;margin-bottom: 5px;">用户积分统计图</h4>
						<div style="display: flex;align-items: center;">
							<el-select v-model="state.users.companys" filterable placeholder="请选择所属公司" autocomplete="off" size="small" style="margin-right: 10px;" clearable>
								<el-option v-for="(item, index) in state.companys" :key="item.id" :label="item.title"
									:value="item.id"></el-option>
							</el-select>
							<el-date-picker v-model="state.users.timeInterval" type="daterange" range-separator="-"
								start-placeholder="开始时间" end-placeholder="结束时间"
								:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X'
								:shortcuts="shortcuts" size="small" />
							<el-button type="primary" @click="getShujuUser(state.users.timeInterval,state.users.companys)" size="small"
								style="margin-left: 10px;">筛选</el-button>
						</div>
					</div>
					<div style="height: calc(100% - 54px)" ref="homeBarUserRef"></div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-three">
			<el-col :xs="24" class="home-media" v-loading="state.uaTableData.loading">
				<div class="home-card-item" style="height: auto">
					<div style="display: flex;justify-content: space-between;margin-bottom: 10px;margin-top: 10px;">
						<h4 style="font-size: 15px;margin-bottom: 5px;">设备统计</h4>
						<div style="display: flex;align-items: center;">
							<el-select multiple v-model="state.uaTableData.param.company_id" filterable placeholder="请选择所属公司" autocomplete="off" size="small" style="margin-right: 10px;" clearable>
								<el-option v-for="(item, index) in state.companys" :key="item.id" :label="item.title"
									:value="item.id"></el-option>
							</el-select>
							<el-date-picker v-model="state.uaTableData.param.timeInterval" type="datetimerange" range-separator="-"
								start-placeholder="开始时间" end-placeholder="结束时间"
								:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X'
								:shortcuts="shortcuts" size="small" />
							<el-button type="primary" @click="onHandleCurrentChange(1)" size="small"
								style="margin-left: 10px;">筛选</el-button>
						</div>
					</div>
					<el-table :data="state.uaTableData.data" style="width: 100%">
						<el-table-column prop="time" label="日期" show-overflow-tooltip align="center"></el-table-column>
						<el-table-column label="总设备数" show-overflow-tooltip align="center">
							<template #default="scope">
								{{ scope.row.windows_count + scope.row.mac_count + scope.row.linux_count + scope.row.android_count + scope.row.other_count + scope.row.ipod_count + scope.row.ipad_count + scope.row.iphone_count + scope.row.unix_count }}
							</template>
						</el-table-column>
						<el-table-column prop="windows_count" label="Windows" show-overflow-tooltip align="center"></el-table-column>
						<el-table-column prop="mac_count" label="Mac" show-overflow-tooltip align="center"></el-table-column>
						<el-table-column prop="linux_count" label="Linux" show-overflow-tooltip align="center">
							<template #default="scope">
								{{ scope.row.linux_count + scope.row.unix_count }}
							</template>
						</el-table-column>
						<el-table-column prop="ios_count" label="iOS" show-overflow-tooltip align="center">
							<template #default="scope">
								{{ scope.row.ipod_count + scope.row.ipad_count + scope.row.iphone_count }}
							</template>
						</el-table-column>
						<el-table-column prop="android_count" label="Android" show-overflow-tooltip align="center"></el-table-column>
						<el-table-column prop="other_count" label="其他" show-overflow-tooltip align="center"></el-table-column>
						<el-table-column label="移动设备占比" show-overflow-tooltip align="center">
							<template #default="scope">
								<span class="baifenbi" v-if="scope.row.windows_count + scope.row.mac_count + scope.row.linux_count + scope.row.android_count + scope.row.other_count + scope.row.ipod_count + scope.row.ipad_count + scope.row.iphone_count + scope.row.unix_count > 0">
									{{ ((scope.row.android_count + scope.row.ipod_count + scope.row.ipad_count + scope.row.iphone_count) / (scope.row.windows_count + scope.row.mac_count + scope.row.linux_count + scope.row.android_count + scope.row.other_count + scope.row.ipod_count + scope.row.ipad_count + scope.row.iphone_count + scope.row.unix_count) * 100).toFixed(2) }}%
								</span>
								<span v-else class="baifenbi">0%</span>	
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						@size-change="onHandleSizeChange"
						@current-change="onHandleCurrentChange"
						class="mt15"
						hide-on-single-page
						v-model:current-page="state.uaTableData.param.page"
						background
						v-model:page-size="state.uaTableData.param.limit"
						layout="prev, pager, next"
						size="default"
						:total="state.uaTableData.total"
					>
					</el-pagination>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup name="home">
import { reactive, onMounted, ref, watch, nextTick, onActivated, markRaw } from 'vue';
import * as echarts from 'echarts';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { commApi } from '/@/api/comm/index';
// 定义变量内容
const homeLineRef = ref();
const homePieRef = ref();
const homeBarRef = ref();
const homeBarUserRef = ref();
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);

import tri from '../../assets/tri.svg'
import tyue from '../../assets/tyue.svg'
import tzhou from '../../assets/tzhou.svg'
import tzong from '../../assets/tzong.svg'
const state = reactive({
	loading:true,
	loading1:true,
	loading2: true,
	loading3: true,
	global: {
		homeChartOne: null,
		homeChartTwo: null,
		homeCharThree: null,
		homeCharFour: null,
		dispose: [null, '', undefined],
	},
	timeInterval: [],
	company_id:'',
	companys:[],
	platform_id:'',
	paltform:[],


	timeIntervalCompany:[],

	users:{
		timeInterval:[],
		companys:undefined,
	},

	uaTableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			timeInterval:[],
			company_id:undefined,
			page: 1,
			limit: 10,
		},
	},

	homeOne: [
		null,
		null,
		null,
		null
	],
	myCharts: [],
	charts: {
		theme: '',
		bgColor: '',
		color: '#303133',
	},
});

const shortcuts = [
	{
		text: 'Yesterday',
		value: () => {
			const now = new Date()
			const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59, 999) // 昨天的最后一秒
			const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0, 0) // 昨天的第一秒
			return [start, end]
		},
	},
	{
		text: 'Last 7 days',
		value: () => {
			const end = new Date()
			end.setHours(23, 59, 59, 999) // 当天最后一秒
			const start = new Date()
			start.setTime(end.getTime() - 3600 * 1000 * 24 * 6) // 近7天前的第一秒
			start.setHours(0, 0, 0, 0)
			return [start, end]
		},
	},
	{
		text: 'Last month',
		value: () => {
			const end = new Date()
			end.setHours(23, 59, 59, 999) // 当天最后一秒
			const start = new Date()
			start.setTime(end.getTime() - 3600 * 1000 * 24 * 29) // 近1个月前的第一秒
			start.setHours(0, 0, 0, 0)
			return [start, end]
		},
	},
];


// 折线图
const initLineChart = (time, earn, final) => {
	if (!state.global.dispose.some((b) => b === state.global.homeChartOne)) state.global.homeChartOne.dispose();
	state.global.homeChartOne = markRaw(echarts.init(homeLineRef.value, state.charts.theme));
	const option = {
		backgroundColor: state.charts.bgColor,
		title: {
			text: '调查积分统计图',
			x: 'left',
			textStyle: { fontSize: '15', color: state.charts.color },
		},
		grid: { top: 70, right: 20, bottom: 30, left: 60 },
		tooltip: { trigger: 'axis' },
		legend: { data: ['成功', '核减'], right: 0 },
		xAxis: {
			data: time,
			boundaryGap: false, // 防止两端空白
		},
		yAxis: [
			{
				type: 'value',
				splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
			},
		],
		series: [
			{
				name: '成功',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: earn,
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
				lineStyle: { color: '#9E87FF' },
				itemStyle: { color: '#9E87FF', borderColor: '#9E87FF' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#9E87FFb3' },
						{ offset: 1, color: '#9E87FF03' },
					]),
				},
				emphasis: {
					itemStyle: {
						color: {
							type: 'radial',
							x: 0.5,
							y: 0.5,
							r: 0.5,
							colorStops: [
								{ offset: 0, color: '#9E87FF' },
								{ offset: 0.4, color: '#9E87FF' },
								{ offset: 0.5, color: '#fff' },
								{ offset: 0.7, color: '#fff' },
								{ offset: 0.8, color: '#fff' },
								{ offset: 1, color: '#fff' },
							],
						},
						borderColor: '#9E87FF',
						borderWidth: 2,
					},
				},
			},
			{
				name: '核减',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: final,
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
			},
		],
	};
	state.global.homeChartOne.setOption(option);
	state.myCharts.push(state.global.homeChartOne);
};
// 饼图
const initPieChart = (round_chart) => {
	if (!state.global.dispose.some((b) => b === state.global.homeChartTwo)) state.global.homeChartTwo.dispose();
	state.global.homeChartTwo = markRaw(echarts.init(homePieRef.value, state.charts.theme));
	round_chart = round_chart.filter(({ platform_name }) => platform_name !== null);
	// var getname = round_chart.map(item => item.platform_name);
	var getname = round_chart.map(item => item.platform_name);
	var data = [];
	data = round_chart.map(({ platform_num, platform_name, earn_pay, final_pay }) => ({ name: platform_name, value: platform_num, earn_pay,final_pay }));

	const colorList = generateUniqueRandomColors(data.length);

	const option = {
		backgroundColor: state.charts.bgColor,
		// title: {
		// 	text: '平台做题数量统计',
		// 	x: 'left',
		// 	textStyle: { fontSize: '15', color: state.charts.color },
		// },
		tooltip: {
			trigger: 'item', formatter: (data) => {
				return `
				<div>
					<div style="display: flex;align-items: center;justify-content: space-between;">
						<div>
							${data.marker}
							<span>${data.data.name}</span>
						</div>
						<div style="margin-left:20px">${data.data.value}题</div>
					</div>
					<div style="display:flex;margin-left:18px;color:#409eff">
						${data.data.earn_pay} Points
					</div>
					<div style="display:flex;margin-left:18px;color:red">
						${data.data.final_pay} Points
					</div>
				</div>
			`
			}
		},
		graphic: {
			elements: [
				{
					type: 'image',
					z: -1,
					style: {
						image: themeConfig.value.isIsDark
							? ''
							: '',
						width: 230,
						height: 230,
					},
					left: '16.5%',
					top: 'center',
				},
			],
		},
		legend: {
			type: 'scroll',
			orient: 'vertical',
			right: '0%',
			left: '65%',
			top: 'center',
			itemWidth: 14,
			itemHeight: 14,
			data: getname,
			textStyle: {
				rich: {
					name: {
						fontSize: 14,
						fontWeight: 400,
						width: 200,
						height: 35,
						padding: [0, 0, 0, 60],
						color: state.charts.color,
					},
					rate: {
						fontSize: 15,
						fontWeight: 500,
						height: 35,
						width: 40,
						padding: [0, 0, 0, 30],
						color: state.charts.color,
					},
				},
			},
		},
		series: [
			{
				type: 'pie',
				radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
				center: ['32%', '50%'],
				itemStyle: {
					color: function (params) {
						return colorList[params.dataIndex];
					},
				},
				label: { show: false },
				labelLine: { show: false },
				data: data,
			},
		],
	};
	state.global.homeChartTwo.setOption(option);
	state.myCharts.push(state.global.homeChartTwo);
};
// 柱状图
const initBarChart = (platform_name, earn, final) => {
	if (!state.global.dispose.some((b) => b === state.global.homeCharThree)) state.global.homeCharThree.dispose();
	state.global.homeCharThree = markRaw(echarts.init(homeBarRef.value, state.charts.theme));
	const option = {
		backgroundColor: state.charts.bgColor,
		// title: {
		// 	text: '公司积分统计图',
		// 	x: 'left',
		// 	textStyle: { fontSize: '15', color: state.charts.color },
		// },
		grid: { top: 70, right: 20, bottom: 30, left: 60 },
		tooltip: { trigger: 'axis' },
		legend: { data: ['成功', '核减'], right: 0 },
		xAxis: {
			data: platform_name,
			boundaryGap: false, // 防止两端空白
		},
		yAxis: [
			{
				type: 'value',
				splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
			},
		],
		series: [
			{
				name: '成功',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: earn,
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
				lineStyle: { color: '#9E87FF' },
				itemStyle: { color: '#9E87FF', borderColor: '#9E87FF' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#9E87FFb3' },
						{ offset: 1, color: '#9E87FF03' },
					]),
				},
				emphasis: {
					itemStyle: {
						color: {
							type: 'radial',
							x: 0.5,
							y: 0.5,
							r: 0.5,
							colorStops: [
								{ offset: 0, color: '#9E87FF' },
								{ offset: 0.4, color: '#9E87FF' },
								{ offset: 0.5, color: '#fff' },
								{ offset: 0.7, color: '#fff' },
								{ offset: 0.8, color: '#fff' },
								{ offset: 1, color: '#fff' },
							],
						},
						borderColor: '#9E87FF',
						borderWidth: 2,
					},
				},
			},
			{
				name: '核减',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: final,
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
			},
		],
	};
	state.global.homeCharThree.setOption(option);
	state.myCharts.push(state.global.homeCharThree);
};
// 用户排行
const initUserChart = (names, earns, finals) => {
	if (!state.global.dispose.some((b) => b === state.global.homeCharFour)) state.global.homeCharFour.dispose();
	state.global.homeCharFour = markRaw(echarts.init(homeBarUserRef.value, state.charts.theme));
	// 创建一个包含名称和差值（earns - finals）的标签数组
	// 创建一个包含名称和差值（earns - finals）的标签数组
	const xAxisLabels = names.map((name, index) => {
		const diff = earns[index] * 1 + finals[index] * 1;
		return  parseFloat(diff).toFixed(2)
	});
	console.log(xAxisLabels);
	console.log(earns)
	
	const option = {
		backgroundColor: state.charts.bgColor,
		grid: { top: 70, right: 20, bottom: 30, left: 60 },
		tooltip: { trigger: 'axis' },
		legend: { data: ['成功', '核减', '实际']},
		xAxis: {
			data: names, // 使用格式化后的标签数组
		},
		yAxis: [
			{
				type: 'value',
				splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
			},
		],
		toolbox: {
			show: true,
			feature: {
			dataView: { show: true, readOnly: false },
			magicType: { show: true, type: ['line', 'bar'] },
			restore: { show: true },
			saveAsImage: { show: true }
			}
		},
		series: [
			{
				name: '成功',
				type: 'bar',
				barWidth: '20%', // 设置柱子的宽度
				data: earns,
				itemStyle: {
					color: '#0194f7', // 设置柱子的颜色
					borderColor: '#0194f7',
				},
				label: {
					show: true, // 显示柱状图上的数字
					position: 'top', // 设置数字的位置
					color: '#0194f7', // 设置数字的颜色
					fontSize: 14, // 设置数字的字体大小
				},
			},
			{
				name: '实际',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: xAxisLabels,
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
				lineStyle: { color: '#9E87FF' },
				itemStyle: { color: '#9E87FF', borderColor: '#9E87FF' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#9E87FFb3' },
						{ offset: 1, color: '#9E87FF03' },
					]),
				},
				emphasis: {
					itemStyle: {
						color: {
							type: 'radial',
							x: 0.5,
							y: 0.5,
							r: 0.5,
							colorStops: [
								{ offset: 0, color: '#9E87FF' },
								{ offset: 0.4, color: '#9E87FF' },
								{ offset: 0.5, color: '#fff' },
								{ offset: 0.7, color: '#fff' },
								{ offset: 0.8, color: '#fff' },
								{ offset: 1, color: '#fff' },
							],
						},
						borderColor: '#9E87FF',
						borderWidth: 2,
					},
				},
			},
			{
				name: '核减',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: finals,
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
			},
			
		],
	};
	state.global.homeCharFour.setOption(option);
	state.myCharts.push(state.global.homeCharFour);
};
const getPlats = () => {
	commApi().getPlats().then(res => {
		if(res.data){
			state.companys = res.data.company
			state.paltform = res.data.paltform
		}
	})
}
// 批量设置 echarts resize
const initEchartsResizeFun = () => {
	nextTick(() => {
		for (let i = 0; i < state.myCharts.length; i++) {
			setTimeout(() => {
				state.myCharts[i].resize();
			}, i * 1000);
		}
	});
};
// 批量设置 echarts resize
const initEchartsResize = () => {
	window.addEventListener('resize', initEchartsResizeFun);
};
const getShuju = async () => {
	state.loading = true;
	try {
		let res = await commApi().getTongjiCount()
		if (res.data) {
			state.homeOne = [
				{
					count: res.data.day,
					scale: getincrease(res.data.day, res.data.last_day),
					title: '今日积分',
					icon: tri,
					iconBackcolor: '--next-color-success-lighter',
					iconColor: '--el-color-success',
				},
				{
					count: res.data.week,
					scale: getincrease(res.data.week, res.data.last_week),
					title: '本周积分',
					icon: tzhou,
					iconBackcolor: '--next-color-warning-lighter',
					iconColor: '--el-color-warning',
				},
				{
					count: res.data.month,
					scale: getincrease(res.data.month, res.data.last_month),
					title: '本月积分',
					icon: tyue,
					iconBackcolor: '--next-color-danger-lighter',
					iconColor: '--el-color-danger',
				},
				{
					count: res.data.count,
					title: '总积分',
					icon: tzong,
					iconBackcolor: '--next-color-primary-lighter',
					iconColor: '--el-color-primary',
				}
			]
		}
	} catch (error) {

	}
	state.loading = false;
}
const getShujuLine = async () => {
	state.loading1 = true;
	try {
		let res = await commApi().getTongjiLine()
		if (res.data) {
			let { time, earn, final } = res.data

			initLineChart(time, earn, final);
		}
	} catch (error) {

	}
	state.loading1 = false;
}
const getShujuRound = async (time = undefined,company_id = undefined) => {
	state.loading2 = true;
	try {
		let res = await commApi().getTongjiRound({time,company_id})
		if (res.data) {
			let round_chart = res.data
			initPieChart(round_chart);
			// let plat_form_chart = res.data.plat_form_chart
			// console.log(plat_form_chart);
			// initBarChart(plat_form_chart.company_name, plat_form_chart.earn, plat_form_chart.final);
		}
	} catch (error) {

	}
	state.loading2 = false;
}
const getShujuPlatform = async (company_last = undefined,platform_id = undefined) => {
	state.loading3 = true;
	try {
		let res = await commApi().getTongjiPlatform({company_last,platform_id})
		if (res.data) {
			let plat_form_chart = res.data
			initBarChart(plat_form_chart.company_name, plat_form_chart.earn, plat_form_chart.final);
		}
	} catch (error) {

	}
	state.loading3 = false;
}
const getShujuUser = async (time = undefined,company_id = undefined) => {
	state.loading4 = true;
	try {
		let res = await commApi().getTongjiCompany_pay({company_id,time})
		if (res.data) {
			let users = res.data
			let names = []
			let earns = []
			let finals = []
			users.forEach(item => {
				names.push(item.name)
				earns.push(parseFloat(item.count).toFixed(2))
				finals.push(parseFloat(item.cut).toFixed(2))
			})
			initUserChart(names, earns, finals);
		}
	} catch (error) {

	}
	state.loading4 = false;
}

const getincrease = (newdata, olddata) => {
	newdata = Number(newdata);
	olddata = Number(olddata);
	// 计算涨幅或降幅的数值差
	const difference = newdata - olddata;
	let changePercentage;
	if (olddata !== 0) {
		// 计算涨幅或降幅的比例
		changePercentage = ((difference / olddata) * 100).toFixed(2);
	} else {
		if (difference > 0) {
			changePercentage = Infinity; // 涨幅为正无穷大
		} else if (difference < 0) {
			changePercentage = -Infinity; // 降幅为负无穷大
		} else {
			changePercentage = 0; // 无变化
		}
	}
	return changePercentage;
}

const generateRandomColor = () => {
	const letters = "0123456789ABCDEF";
	let color = "#";

	for (let i = 0; i < 6; i++) {
		color += letters[Math.floor(Math.random() * 16)];
	}

	return color;
}

const generateUniqueRandomColors = (length) => {
	if (length <= 0) {
		return [];
	}
	const colors = [];
	while (colors.length < length) {
		const color = generateRandomColor();

		if (!colors.includes(color)) {
			colors.push(color);
		}
	}
	return colors;
}

// 分页改变
const onHandleSizeChange = (val) => {
	state.uaTableData.param.limit = val;
	getUaSysType();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	state.uaTableData.param.page = val;
	getUaSysType();
};
const getUaSysType = async () => {
	state.uaTableData.loading = true;
	try {
		let res = await commApi().getTongjiUatype(state.uaTableData.param)
		if (res.data) {
			state.uaTableData.data = res.data.list;
			state.uaTableData.total = res.data.total;
		}
	} catch (error) {

	}
	state.uaTableData.loading = false;
}
// 页面加载时
onMounted(() => {
	initEchartsResize();
	getPlats()
	getShuju()
	getShujuLine()
	getShujuRound()
	getShujuPlatform()
	getShujuUser()
	getUaSysType()
});
// 由于页面缓存原因，keep-alive
onActivated(() => {
	initEchartsResizeFun();
});
// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
	() => isTagsViewCurrenFull.value,
	() => {
		initEchartsResizeFun();
	}
);
// 监听 pinia 中是否开启深色主题
watch(
	() => themeConfig.value.isIsDark,
	(isIsDark) => {
		nextTick(() => {
			state.charts.theme = isIsDark ? 'dark' : '';
			state.charts.bgColor = isIsDark ? 'transparent' : '';
			state.charts.color = isIsDark ? '#dadada' : '#303133';
			// setTimeout(() => {
			// 	initLineChart();
			// }, 500);
			// setTimeout(() => {
			// 	initPieChart();
			// }, 700);
			// setTimeout(() => {
			// 	initBarChart();
			// }, 1000);
		});
	},
	{
		deep: true,
		immediate: true,
	}
);
</script>

<style scoped lang="scss">
$homeNavLengh: 8;

.home-container {
	overflow: hidden;

	.home-card-one,
	.home-card-two,
	.home-card-three {
		.home-card-item {
			width: 100%;
			height: 130px;
			border-radius: 4px;
			transition: all ease 0.3s;
			padding: 20px;
			overflow: hidden;
			background: var(--el-color-white);
			color: var(--el-text-color-primary);
			border: 1px solid var(--next-border-color-light);

			&:hover {
				box-shadow: 0 2px 12px var(--next-color-dark-hover);
				transition: all ease 0.3s;
			}

			&-icon {
				width: 70px;
				height: 70px;
				border-radius: 100%;
				flex-shrink: 1;

				i {
					color: var(--el-text-color-placeholder);
				}
			}

			&-title {
				font-size: 15px;
				font-weight: bold;
				height: 30px;
			}
		}
	}

	.home-card-one {
		@for $i from 0 through 3 {
			.home-one-animation#{$i} {
				opacity: 0;
				animation-name: error-num;
				animation-duration: 0.5s;
				animation-fill-mode: forwards;
				animation-delay: calc($i/4) + s;
			}
		}
	}

	.home-card-two,
	.home-card-three {
		.home-card-item {
			height: 400px;
			width: 100%;
			overflow: hidden;

			.home-monitor {
				height: 100%;

				.flex-warp-item {
					width: 25%;
					height: 111px;
					display: flex;

					.flex-warp-item-box {
						margin: auto;
						text-align: center;
						color: var(--el-text-color-primary);
						display: flex;
						border-radius: 5px;
						background: var(--next-bg-color);
						cursor: pointer;
						transition: all 0.3s ease;

						&:hover {
							background: var(--el-color-primary-light-9);
							transition: all 0.3s ease;
						}
					}

					@for $i from 0 through $homeNavLengh {
						.home-animation#{$i} {
							opacity: 0;
							animation-name: error-num;
							animation-duration: 0.5s;
							animation-fill-mode: forwards;
							animation-delay: calc($i/10) + s;
						}
					}
				}
			}
		}
	}
}
.baifenbi{
	background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1));
	color: rgb(22 101 52 / var(--tw-text-opacity, 1));
	padding-top:0.25rem;
	padding-bottom:0.25rem;
	padding-left:0.5rem;
	padding-right:0.5rem;
	font-size: 0.875rem;
	border-radius:99999px;
}
</style>
